﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Common
{
    public class CommonClass
    {
        /// <summary>
        /// 默认编码格式
        /// </summary>
        private Encoding encode = Encoding.GetEncoding("gb2312");

        #region List与Json转换
        /// <summary>
        /// 指定对象转换为指定编码格式的Json对象
        /// </summary>
        /// <param name="T"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string ObjToJson<T>(T data, Encoding encoding)
        {
            if (data == null)
                return string.Empty;
            this.encode = encoding;
            return ObjToJson<T>(data);
        }

        /// <summary>
        /// 指定对象转换为gb2312编码格式的Json对象
        /// </summary>
        /// <param name="T"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string ObjToJson<T>(T data)
        {
            if (data == null)
                return string.Empty;
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, data);
                    return encode.GetString(ms.ToArray());
                }
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 把gb2312编码格式的Json转换为指定对象类型
        /// </summary>
        /// <param name="json">指定Json对象</param>
        /// <param name="type">需要转化的对象类型</param>
        /// <returns></returns>
        public object JsonToObj(string json, Type type)
        {
            if (json == string.Empty)
                return null;
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(type);
                using (MemoryStream ms = new MemoryStream(encode.GetBytes(json)))
                {
                    return serializer.ReadObject(ms);
                }
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 把指定编码格式的Json转换为指定对象类型
        /// </summary>
        /// <param name="json">指定Json对象</param>
        /// <param name="type">需要转化的对象类型</param>
        /// <param name="encoding">编码格式</param>
        /// <returns></returns>
        public object JsonToObj(string json, Type type, Encoding encoding)
        {
            if (encoding == null)
                return null;
            this.encode = encoding;
            return JsonToObj(json, type);
        }
        #endregion
    }
}
